from django.shortcuts import render,redirect
from django.http import JsonResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from .models import InformationBox,GraphService
from .forms import LoginForm
from .tools import graph,tool
import random
import json


#修饰器
def GetEmail(func):
    def warpper(request):
        name = None
        if request.method == "POST":
            name = request.POST.get("InputEmail","None")
        load = func(request,name)
        return load
    return warpper
def UpdateInfo(request,username):
    Items = tool.GraphTool()
    UserItem = User.objects.get(username=username)
    for _ in Items:
        if _['username'] == username:
            try:
                graphItem = GraphService.objects.get(user=UserItem, name=_['name'])
                graphItem.radar_data = _['radarSize']
                graphItem.radar_labels = _['radarLabels']
                graphItem.pie_data = _['pieSize']
                graphItem.pie_labels = _['pieLabels']
                graphItem.save()
            except GraphService.DoesNotExist:
                graph_service = GraphService(
                    user=UserItem,  # 确保这里传入的是User实例
                    name=_['name'],
                    radar_data=_['radarSize'],
                    radar_labels=_['radarLabels'],
                    pie_data=_['pieSize'],
                    pie_labels=_['pieLabels'],
                )
                graph_service.save()
#页面函数
def LoadName(request):
    #验证是否登录
    if request.user.is_authenticated:
        username = request.user.username
    else:
        username = None
    return username
def LogoutInfo(request):
    logout(request)
    return redirect('index')
def LoginInfo(request):

    page_name = 'login.html'
    context = {}
    height = 400
    if request.method == 'POST':
        #登录表格
        form = LoginForm(data=request.POST)
        if form.is_valid():
            username = form.cleaned_data['username']
            password = form.cleaned_data['password']
            user = authenticate(request, username=username, password=password)
            if user is not None:
                #登录成功
                UpdateInfo(request=request, username=form.cleaned_data['username'])
                login(request, user)
                return redirect('index')
            else:
                height = 600
                form.add_error(None, '用户名或密码错误')
    else:
        form = LoginForm()
    context['height'] = height
    context['form'] = form
    return render(request, template_name=page_name, context=context)
@GetEmail
def LodeInformation(request,name):
    page_name = 'information.html'
    username = LoadName(request)
    context = {}
    Information = InformationBox.objects.filter(RxUser=username)
    usersInformation = [[i+1,Information[i]] for i in range(len(Information))]

    Now = usersInformation[0][1].id
    if request.method == "GET":
        Now = request.GET.get("Now",usersInformation[0][1].id)

    url = InformationBox.objects.get(id=Now).url

    context['url'] = url
    context['Now'] = Now
    context['username'] = username
    context['usersInformation'] = usersInformation
    page = render(request,template_name=page_name,context=context)

    return page
@GetEmail
def IndexInfo(request,name):
    #初始页面函数
    page_name = "index.html"
    context = {}
    username = LoadName(request)
    context['username'] = username
    page = render(request,template_name=page_name,context=context)
    return page

def ServiceInfo(request):
    #服务页面函数
    page_name = "service-details.html"
    context = {}
    name = "admin"

    pos = 'pieChart'
    if request.method == "GET":
        pos = request.GET.get("pos", 'pieChart')

    try:
        userItem = User.objects.get(username=name)
        userdata = userItem.AnalyseData.all()
        logs = {}
        TheFirstUser = userdata[0].name
        names = []

        for _ in userdata:
            id = _.id
            name = _.name
            names.append(name)
            radar_data = _.radar_data
            radar_labels = _.radar_labels
            pie_data = _.pie_data
            pie_labels = _.pie_labels
            logs[name] = {
                'id': id,
                'radar_data': radar_data,
                'radar_labels': radar_labels,
                'pie_data': pie_data,
                'pie_labels': pie_labels,
            }

        AnalyseName = TheFirstUser
        if request.method == "GET":
            pos = request.GET.get("pos", 'chatBot')
            AnalyseName = request.GET.get("name", TheFirstUser)

        item = logs[AnalyseName]

        if pos == 'pieChart':
            context['labels'] = item['pie_labels']
            context['data'] = item['pie_data']
            context['colors'] = [f'rgb({random.randint(100,125)},{random.randint(200,225)},{random.randint(125,255)})'
            for _ in range(len(item['pie_data']))]
            page_name = 'service-pie.html'

        elif pos == 'barChart':
            context['labels'] = item['radar_labels']
            context['data'] = item['radar_data']
            context['colors'] = [
                f'rgb({random.randint(100, 125)},{random.randint(200, 225)},{random.randint(125, 255)})'
                for _ in range(len(item['radar_data']))]
            page_name = 'service-bar.html'

        elif pos == 'chatBot':
            page_name = 'service-chat.html'

        context['Graph'] = '#'+pos
        context['Analyse'] = AnalyseName
        context['names'] = names

    except IndexError:
        errorInfo = "目前您还没有做过测试哦，数据暂无"
        context['lack'] = errorInfo

    context['pos'] = pos
    context['items'] = ['chatBot','pieChart', 'barChart']
    context['username'] = name
    page = render(request,template_name=page_name,context=context)
    return page
def FastUrl(requset):
    #测试用跳转界面
    return redirect("index")
@login_required(login_url='login')
def Test(request):
    username = LoadName(request)
    context = {}
    page_name = "test.html"
    userItem = User.objects.get(username=username)
    userdata = userItem.AnalyseData.all()

    testdata = userdata[0]
    piedata = list(map(int,testdata.pie_data))
    pielabel = testdata.pie_labels

    context['piedata'] = piedata
    context['pielabel'] = pielabel
    context['username'] = username


    page = render(request,page_name,context)
    return page

def ChatInfo(request):
    page_name = 'chat.html'
    context = {}
    page = render(request=request, template_name=page_name, context=context)
    return page
